#!/usr/bin/python3

###############################################################################
#                                                                             #
#    L3q - Light, light, lightweight queue                                    #
#    Copyright (C) 2023  Marcus Pedersén marcus.pedersen@slu.se               #
#                                                                             #
#    This program is free software: you can redistribute it and/or modify     #
#    it under the terms of the GNU General Public License as published by     #
#    the Free Software Foundation, either version 3 of the License, or        #
#    (at your option) any later version.                                      #
#                                                                             #
#    This program is distributed in the hope that it will be useful,          #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
#    GNU General Public License for more details.                             #
#                                                                             #
#    You should have received a copy of the GNU General Public License        #
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.    #
#                                                                             #
###############################################################################


import sqlite3
import time, datetime
import gzip
import shutil
import os
import glob
import schedule # type: ignore
import signal


class L3QBackup:
    def __init__(self, conf):
        '''
        Init and sets the required
        variables from conf object.
        To start the backup call function
        schedule_backup() and
        the backup will start to run
        at specified time.
        '''
        self.hour = conf.db_backup_hour
        self.minute = conf.db_backup_minute
        self.max_no_bkps = conf.db_backup_max_count
        self.logger = conf.logger
        self.db_file = conf.db_file
        self.db_bkp_dir = conf.db_backup_directory
        self.logger.info('Starting L3QBackup ...')

        signal.signal(signal.SIGTERM, self.terminate)
        
        
    def make_db_backup(self):
        '''
        Makes the backup for the 
        sqlite3 database.
        Creates a backup file with 
        a name containing date, time 
        and a suffix with .bkp.gz
        Backup is is zipped with gzip,
        stored in backup directory and
        backup directory is updated 
        and if ti many backups are available
        the oldest backups are deleted.
        The scheduler is started again.
        '''

        now = datetime.datetime.now()
        db_name = os.path.basename(self.db_file)
        bkp_name = '{}_{}.bkp'.format(now.strftime('%Y%m%d_%H%M%S'), db_name)
        bkp_name = os.path.join(self.db_bkp_dir, bkp_name)

        try:
            conn = sqlite3.connect(self.db_file)
            bkp_conn = sqlite3.connect(bkp_name)

            conn.backup(bkp_conn)
            conn.close()
            bkp_conn.close()

            with open(bkp_name, 'rb') as f_in:
                with gzip.open(bkp_name + '.gz', 'wb') as f_out:
                    shutil.copyfileobj(f_in, f_out)
    
            os.remove(bkp_name)
        except Exception as e:
            self.logger.error('L3QBackup: Falied to create and gzip backup: {}, {}'.format(bkp_name, e))
        else:
            self.logger.info('L3QBackup: Database backup succesfully created: {}'.format(bkp_name + '.gz'))

        try:
            bkp_files = glob.glob('*.bkp.gz')
            if(len(bkp_files) > self.max_no_bkps):
                bkp_files.sort()
                bkp_files.reverse()

                for f in bkp_files[self.max_no_bkps:]:
                    os.remove(f)
        except Exception as e:
            self.logger.error('L3QBackup: Falied to clean up old backups: {}'.format(e))
            

        
    def schedule_backup(self):
        '''
        The scheduler is setup so
        the backup function is run
        the next day at specified time.
        '''

        self.running =True
        stime = ''

        if(self.hour < 10):
            stime = '0{}:'.format(self.hour)
        else:
            stime = '{}:'.format(self.hour)

        if(self.minute < 10):
            stime += '0{}'.format(self.minute)
        else:
            stime += '{}'.format(self.minute)

        schedule.every().day.at(stime).do(self.make_db_backup)

        while self.running:
            schedule.run_pending()
            time.sleep(1)
            


    def terminate(self, signum, frame):
        self.logger.info('L3QBackup: Closing down ...')
        self.running = False
        self.logger.info('L3QBackup: Terminating')


